package com.suncky.frame.paging;

import androidx.paging.PageKeyedDataSource;

import com.suncky.frame.http.DataCallback;
import com.suncky.frame.http.bean.Page;
import com.suncky.frame.http.bean.Result;

import java.util.List;

/**
 * @author gl
 * @time 2021/4/15 15:36
 */
public class PagingCallBack<E,P extends Page,R extends Result<List<E>,P>> extends DataCallback<List<E>,P,R> {
    private PageKeyedDataSource.LoadInitialCallback<Integer, E> initialCallback;
    private PageKeyedDataSource.LoadCallback<Integer, E> loadCallback;
    private int loadType;

    public PagingCallBack(PageKeyedDataSource.LoadInitialCallback<Integer, E> initialCallback, int loadType) {
        this.initialCallback = initialCallback;
        this.loadType = loadType;
    }

    public PagingCallBack(PageKeyedDataSource.LoadCallback<Integer, E> loadCallback, int loadType) {
        this.loadCallback = loadCallback;
        this.loadType = loadType;
    }

    @Override
    public void onSuccess(List<E> data, P page) {
        if (loadType == LoadType.INIT && initialCallback != null) {
            Integer nextPage = null;
            if (page.currentPage() < page.totalPage()) {
                nextPage = page.currentPage() + 1;
            }
            initialCallback.onResult(data, 0, nextPage);
        } else if (loadType == LoadType.APPEND && loadCallback != null) {
            Integer pageKey = null;
            if (page.currentPage() < page.totalPage()) {
                pageKey = page.currentPage() + 1;
            }
            loadCallback.onResult(data, pageKey);
        }
    }

    @Override
    public void onError(int code, String message) {

    }

    public int getLoadType() {
        return loadType;
    }
}
